package cc.kigh.framework.handler.url;

import cc.kigh.common.core.domain.MayBeUrl;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.web.util.UrlUtils;

import java.io.IOException;

/**
 * @author gylang
 * data 2022/2/25
 */
public class PrivateUrlDeserializer extends JsonDeserializer<MayBeUrl> implements Converter<String, MayBeUrl> {

    public static final PrivateUrlDeserializer INSTANCE = new PrivateUrlDeserializer();
    @Override
    public MayBeUrl deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String source = p.getText().trim();

        return getPrivateUrl(source);
    }

    private MayBeUrl getPrivateUrl(String source) {
        if (StrUtil.isNotEmpty(source)) {
            if (UrlUtils.isAbsoluteUrl(source)) {
                // 删除url地址后面的参数
                return new MayBeUrl(StrUtil.subBefore(source, "?", true));
            } else {
                return new MayBeUrl(source);
            }
        }

        return null;
    }


    @Override
    public MayBeUrl convert(String source) {
        return getPrivateUrl(source);
    }
}
